import React, { useEffect, useState } from 'react';
import { Table, Card, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import axios from 'axios';

interface AIRecord {
  id: number;
  app: string;
  app_version: string;
  country_code: string;
  storefront: string;
  model_name: string;
  total_tokens: number;
  purchased: boolean;
  product_id1: string;
  status: boolean;
  error_message: string;
}

interface AIRecordsProps {
  token: string;
}

const AIRecords: React.FC<AIRecordsProps> = ({ token }) => {
  const [data, setData] = useState<AIRecord[]>([]);
  const [loading, setLoading] = useState(false);

  const columns: ColumnsType<AIRecord> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '应用',
      dataIndex: 'app',
      key: 'app',
    },
    {
      title: '版本',
      dataIndex: 'app_version',
      key: 'app_version',
    },
    {
      title: '国家',
      dataIndex: 'country_code',
      key: 'country_code',
    },
    {
      title: '商店',
      dataIndex: 'storefront',
      key: 'storefront',
    },
    {
      title: '模型',
      dataIndex: 'model_name',
      key: 'model_name',
    },
    {
      title: 'Token数',
      dataIndex: 'total_tokens',
      key: 'total_tokens',
    },
    {
      title: '已购买',
      dataIndex: 'purchased',
      key: 'purchased',
      render: (purchased: boolean) => (purchased ? '是' : '否'),
    },
    {
      title: '产品ID',
      dataIndex: 'product_id1',
      key: 'product_id1',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: boolean) => (status ? '成功' : '失败'),
    },
    {
      title: '错误信息',
      dataIndex: 'error_message',
      key: 'error_message',
    },
  ];

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        console.log('正在请求数据，token:', token);
        const response = await axios.get('/api/ai-records', {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
        });
        console.log('API响应:', response);
        if (response.data) {
          setData(response.data);
        } else {
          message.error('返回数据格式不正确');
        }
      } catch (error: any) {
        console.error('API请求错误:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          message.error(`获取数据失败: ${error.response.data.error || '未知错误'}`);
        } else if (error.request) {
          console.error('请求错误:', error.request);
          message.error('无法连接到服务器，请检查网络连接');
        } else {
          console.error('错误:', error.message);
          message.error(`请求失败: ${error.message}`);
        }
      } finally {
        setLoading(false);
      }
    };

    if (token) {
      fetchData();
    }
  }, [token]);

  return (
    <Card title="AI记录">
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        scroll={{ x: true }}
        size="small"
        rowClassName={(record, index) => index % 2 === 0 ? 'table-row-light' : 'table-row-dark'}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: ['10', '20', '50', '100'],
          position: ['bottomRight']
        }}
      />
    </Card>
  );
};

export default AIRecords; 